// 加载http模块
let http = require('http')
let Cheerio = require('cheerio')
let fs = require('fs')
let path = require('path')
//打印信息
let prinfInfo = require('./server/print')
let qiuniu = require('./server/qiniu')
//获取英雄详细信息
let Hero = require('./server/hero')
//定义网络爬取的地址
let url = 'http://lol.duowan.com/hero/'
var i = 0;
http.get(url, (res) => {
  let html = ''
  //获取页面数据
  res.on('data', (data) => {
    html += data;
  })
  res.on('end', () => {
    //过滤页面信息
    //TODO: 获取枪支的截图
    var listData = getMyowenPage(html)
    //TODO:打印信息
    prinfInfo(listData);
    //循环
    if (!Boolean(listData)) {
      return;
    }
    // setInterval(function () {   loop(listData); }, 10000);
  })
}).on('error', () => {
  console.log('获取数据出错')
})

function getMyowenPage(html) {
  console.log(html);

  if (html) {
    var $ = Cheerio.load(html, {ignoreWhitespace: true})
    //轮播图数据
    var lolHero = []
    //轮播图信息列表遍历
    console.log('length', $('#jSearchHeroDiv li').length);

    $('#champion_list li').each(function (index, items) {
      // console.log($(this).find('.champion_icon')[0].attribs.src);
      let [imgSrc,
        name,
        link] = [
        $(this)
          .find('.champion_icon')
          .attr('src'),
        $(this)
          .find('.champion_name')
          .text(),
        $(this)
          .find('.lol_champion')
          .attr('href')
      ];
      console.log($(this).children('img').attr('src'))
      console.log(imgSrc, name, link);

      lolHero.push({imgsrc: imgSrc, name: name, details: '', link: link})
    })
  } else {
    console.log('false');
    return false
  }
  return lolHero
}

//  轮询获取每个英雄的详细数据
function loop(param) {
  i++;
  fs.readFile('lol.json', 'utf-8', function (err, data) {
    if (err) {
      throw err;
    }
    console.log('读取成功', i);
    prinfInfo(param)
    //定时轮询 每个页面的英雄详情页 获取数据 console.log(data);
    return;
    param.map((items) => {
      http.get(items.link, (res) => {
        let html = ''
        //获取页面数据
        res.on('data', (data) => {
          html += data;
        })
        console.log(html);
        res.on('end', () => {
          //过滤页面信息
          //TODO: 获取枪支的截图
          let heroDetials = Hero(html, link);
          //TODO:打印信息
          prinfInfo(heroDetials);
        })
      }).on('error', () => {
        console.log('获取数据出错')
      })
    })

  })
}